package Thread;

import java.util.TreeMap;

/**多线程打印ABC*/
public class demo26 {
    public static void main(String[] args) throws InterruptedException {
        Object o1 = new Object();
        Object o2 = new Object();
        Object o3 = new Object();

        Thread t1 = new Thread(()->{
           try {
               for (int i = 0; i < 10; i++) {
                   synchronized (o1) {
                       o1.wait();
                   }
                   System.out.print("A");
                   synchronized (o2) {
                       o2.notify();
                   }
               }
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
        });


        Thread t2 = new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (o2) {
                        o2.wait();
                    }
                    System.out.print("B");
                    synchronized (o3) {
                        o3.notify();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t3 = new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (o3) {
                        o3.wait();
                    }
                    System.out.println("C");
                    synchronized (o1) {
                        o1.notify();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        t1.start();
        t2.start();
        t3.start();
        // 确保至少有一个线程在开始时是唤醒状态
        // 主线程中, 先通知一次 locker1, 让上述逻辑从 t1 开始执行
        // 需要确保上述三个线程都执行到 wait, 再进行 notify
        Thread.sleep(1000);
        synchronized (o1) {
            o1.notify();
        }
    }
}
